import { UserConfigExport, ConfigEnv, loadEnv } from "vite";
import vue from "@vitejs/plugin-vue";
import vueJsx from '@vitejs/plugin-vue-jsx'
import { viteMockServe } from 'vite-plugin-mock'
import { resolve } from "path";
import { wrapperEnv } from "/@/utils/disposeEnv";
// 当前执行node命令时文件夹的地址（工作目录）
const root: string = process.cwd();

// 路径查找
const pathResolve = (dir: string): string => {
  return resolve(__dirname, ".", dir);
};

// 设置别名
const alias: Record<string, string> = {
  "/@": pathResolve("src"),
  "@build": pathResolve("build"),
  "/#/": pathResolve("types"),
  
  //解决开发环境下的警告
  // "vue-i18n": "vue-i18n/dist/vue-i18n.cjs.js"
};
export default ({ command, mode }: ConfigEnv): UserConfigExport => {
  const root = process.cwd();
  const env = loadEnv(mode, root);
  const viteEnv = wrapperEnv(env);
  const { VITE_PUBLIC_PATH, VITE_PORT, } = viteEnv;
  const prodMock = true;
  return {
    base: VITE_PUBLIC_PATH,
    root,
    resolve: {
      alias
    },
    css: {
      // https://github.com/vitejs/vite/issues/5833
      // postcss: {
      //   plugins: [
      //     {
      //       postcssPlugin: "internal:charset-removal",
      //       AtRule: {
      //         charset: atRule => {
      //           if (atRule.name === "charset") {
      //             atRule.remove();
      //           }
      //         }
      //       }
      //     }
      //   ]
      // },
      preprocessorOptions: {

      }
    },
    // 服务端渲染
    server: {
      // 是否开启 https
      https: false,
      // 端口号
      port: VITE_PORT,
      host: "0.0.0.0",
      // 本地跨域代理
      // proxy:
      //   VITE_PROXY_DOMAIN_REAL.length > 0
      //     ? {
      //       [VITE_PROXY_DOMAIN]: {
      //         target: VITE_PROXY_DOMAIN_REAL,
      //         // ws: true,
      //         changeOrigin: true,
      //         rewrite: (path: string) => regExps(path, VITE_PROXY_DOMAIN)
      //       }
      //     }
      //     : null
    },
    plugins: [
      vue(),
      // jsx、tsx语法支持
      vueJsx(),
      // mock配置
      viteMockServe({
        mockPath: 'mock',
        localEnabled: command === 'serve',
        prodEnabled: command !== 'serve' && prodMock,
        //  这样可以控制关闭mock的时候不让mock打包到最终代码内
        injectCode: `
          import { setupProdMockServer } from './mockProdServer';
          setupProdMockServer();
        `,
      }),
    ],

    build: {
      sourcemap: false,
      brotliSize: false,
      // 消除打包大小超过500kb警告
      chunkSizeWarningLimit: 2000
    },
    define: {
      __INTLIFY_PROD_DEVTOOLS__: false,
      // 解决process无效问题
      'process.env': viteEnv

    }
  };
};
